<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <span style="color: red;">说明：单位：元
        </span>
        <a-row>
          <a-col :xs="12" :sm="12">
            <a-form-model-item label="年度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="year">
              <j-dict-select-tag type="list" v-model="model.year" dictCode="year" placeholder="请选择年度"
                @change="handleYearChange" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="赡养人员工资表" :key="refKeys[0]" :forceRender="true">
        <j-editable-table :ref="refKeys[0]" :loading="cwSyrygzbTable.loading" :columns="cwSyrygzbTable.columns"
          :dataSource="cwSyrygzbTable.dataSource" :maxHeight="300" :disabled="formDisabled" :rowNumber="true"
          :rowSelection="true" :actionButton="true" />
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>
import { mapState } from 'vuex'
import { FormTypes, getRefPromise, VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
import { JEditableTableModelMixin } from '@/mixins/JEditableTableModelMixin'
import { validateDuplicateValue } from '@/utils/util'
import { getAction } from '@/api/manage'

export default {
  name: 'CwSyrygzbTjForm',
  mixins: [JEditableTableModelMixin],
  components: {},
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      model: { year: '' }, // 初始为空，由watch同步全局年度
      validatorRules: {
        unit: [
          { required: true, message: '请输入单位!' },
        ],
        year: [
          { required: true, message: '请输入年度!' },
        ],
      },
      addDefaultRowNum: 1,
      refKeys: ['cwSyrygzb'],
      tableKeys: ['cwSyrygzb'],
      activeKey: 'cwSyrygzb',
      confirmLoading: false,
      // 赡养人员工资表
      cwSyrygzbTable: {
        loading: false,
        dataSource: [],
        columns: [
          // {
          //   title: '财政/非财政',
          //   key: 'czFcz',
          //   type: FormTypes.select,
          //   dictCode: "cz_fcz",
          //   width: "200px",
          //   placeholder: '请输入${title}',
          //   defaultValue: '',
          // },
          {
            title: '姓名',
            key: 'name',
            type: FormTypes.input,
            width: "80px",
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '职务',
            key: 'duty',
            type: FormTypes.input,
            width: "80px",
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '岗位工资',
            key: 'postWage',
            type: FormTypes.input,
            width: "80px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [
              {
                // 修改后的正则：仅允许非负数字，支持整数或最多2位小数
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],
          },
          {
            title: '薪级工资',
            key: 'xjgz',
            type: FormTypes.input,
            width: "80px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [
              {
                // 修改后的正则：仅允许非负数字，支持整数或最多2位小数
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],
          },
          {
            title: '生活性补贴',
            key: 'livingAllowance',
            type: FormTypes.input,
            width: "80px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [
              {
                // 修改后的正则：仅允许非负数字，支持整数或最多2位小数
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],
          },
          {
            title: '工作性津贴',
            key: 'gzxjt',
            type: FormTypes.input,
            width: "80px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [
              {
                // 修改后的正则：仅允许非负数字，支持整数或最多2位小数
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],
          },
          {
            title: '卫生费',
            key: 'sanitationFee',
            type: FormTypes.input,
            width: "80px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [
              {
                // 修改后的正则：仅允许非负数字，支持整数或最多2位小数
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],
          },
          {
            title: '回民补贴',
            key: 'hmpt',
            type: FormTypes.input,
            width: "80px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [
              {
                // 修改后的正则：仅允许非负数字，支持整数或最多2位小数
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],
          },
          {
            title: '13%房补',
            key: 'fb',
            type: FormTypes.input,
            width: "80px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [
              {
                // 修改后的正则：仅允许非负数字，支持整数或最多2位小数
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],
          },
          {
            title: '基础绩效奖',
            key: 'jcjxj',
            type: FormTypes.input,
            width: "80px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [
              {
                // 修改后的正则：仅允许非负数字，支持整数或最多2位小数
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],
          },
          {
            title: '应发工资',
            key: 'salary',
            type: FormTypes.input,
            width: "80px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [
              {
                // 修改后的正则：仅允许非负数字，支持整数或最多2位小数
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],
          },
          {
            title: '养老保险',
            key: 'ylbx',
            type: FormTypes.input,
            width: "80px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [
              {
                // 修改后的正则：仅允许非负数字，支持整数或最多2位小数
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],
          },
          {
            title: '医疗保险',
            key: 'ylbxa',
            type: FormTypes.input,
            width: "80px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [
              {
                // 修改后的正则：仅允许非负数字，支持整数或最多2位小数
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],
          },
          {
            title: '失业金',
            key: 'syj',
            type: FormTypes.input,
            width: "80px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [
              {
                // 修改后的正则：仅允许非负数字，支持整数或最多2位小数
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],
          },
          {
            title: '职业年金',
            key: 'zynj',
            type: FormTypes.input,
            width: "80px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [
              {
                // 修改后的正则：仅允许非负数字，支持整数或最多2位小数
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],
          },
          {
            title: '住房公积金',
            key: 'zfgjj',
            type: FormTypes.input,
            width: "80px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [
              {
                // 修改后的正则：仅允许非负数字，支持整数或最多2位小数
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],
          },
          {
            title: '个税',
            key: 'gs',
            type: FormTypes.input,
            width: "80px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [
              {
                // 修改后的正则：仅允许非负数字，支持整数或最多2位小数
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],
          },
          {
            title: '应扣合计',
            key: 'ykhj',
            type: FormTypes.input,
            width: "80px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [
              {
                // 修改后的正则：仅允许非负数字，支持整数或最多2位小数
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],
          },
          {
            title: '实发工资',
            key: 'payoff',
            type: FormTypes.input,
            width: "80px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [
              {
                // 修改后的正则：仅允许非负数字，支持整数或最多2位小数
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],
          },
          {
            title: '取暖费',
            key: 'heatingFee',
            type: FormTypes.input,
            width: "80px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [
              {
                // 修改后的正则：仅允许非负数字，支持整数或最多2位小数
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],
          },
        ]
      },
      url: {
        add: "/cw/cwSyrygzbTj/add",
        edit: "/cw/cwSyrygzbTj/edit",
        cwSyrygzb: { list: '/cw/cwSyrygzbTj/queryCwSyrygzbByMainId' },
        getByYear: '/cw/cwSyrygzbTj/list' // 复用体检表的年度查询接口，后续可自行修改
      },
      isManualChange: false // 标记是否手动修改过表单年度

    }
  },
  props: {
    disabled: {
      type: Boolean,
      default: false,
      required: false
    },
    scene: { // 接收 Modal 传递的场景值
      type: String,
      default: ''
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
    ...mapState({ globalYear: state => state.app.globalYear })

  },
  watch: {
    // 监听全局年度变化，同步到表单（仅当未手动修改时）
    globalYear(newVal) {
      if (!this.isManualChange) {
        this.model.year = newVal
        // 可选：自动触发年度查询，解开注释即可
        // this.handleYearChange(newVal)
      }
    },
    // 监听表单年度变化，标记是否手动修改
    'model.year'(newVal, oldVal) {
      if (oldVal && newVal !== this.globalYear) {
        this.isManualChange = true // 手动修改后，不再同步全局年度
      }
    }
  },

  created() {
    // 初始化时同步全局年度
    this.model.year = this.globalYear
    const scene = this.scene; // 接收 Modal 传递的 scene（add/edit）
    this.currentScene = scene; // 存储到本地变量，后续复用
    console.log(scene)
    if (scene=='add'){
      this. handleYearChange(this.model.year)
    }
  },
  methods: {
    addBefore() {
      this.cwSyrygzbTable.dataSource = []
    },
    getAllTable() {
      let values = this.tableKeys.map(key => getRefPromise(this, key))
      return Promise.all(values)
    },
    editAfter() {
      this.$nextTick(() => { })
      if (this.model.id) {
        let params = { id: this.model.id }
        getAction(this.url.cwSyrygzb.list, params).then(res => {
          if (res.success) {
            this.cwSyrygzbTable.dataSource = res.result.records || []
          }
        }).finally(() => {
          this.cwSyrygzbTable.loading = false
        })
      }
    },
    validateSubForm(allValues) {
      return new Promise((resolve, reject) => {
        Promise.all([]).then(() => {
          resolve(allValues)
        }).catch(e => {
          if (e.error === VALIDATE_NO_PASSED) {
            this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
          } else {
            console.error(e)
          }
        })
      })
    },
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main,
        cwSyrygzbList: allValues.tablesValue[0].values,
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    },
    close() {
      this.visible = false
      this.$emit('close')
      if (this.$refs.form) {
        this.$refs.form.clearValidate();
      }
    },
    async handleYearChange(year) {
      // 清空逻辑：未选择年度时，保留单位，清空其他数据
      if (!year) {
        this.model = { unit: this.model.unit }
        this.cwSyrygzbTable.dataSource = []
        return
      }

      // 加载状态：主表+子表同时加载
      this.confirmLoading = true
      this.cwSyrygzbTable.loading = true

      try {
        // 调用年度查询接口
        const yearResponse = await getAction(this.url.getByYear, { year })

        if (yearResponse.success && yearResponse.result.records.length > 0) {
          const mainRecord = yearResponse.result.records[0]
          // 主表数据回显：保留用户已选的unit和year，合并接口返回的其他字段
          this.model = {
            ...this.model,
            ...mainRecord
          }

          // 使用返回的mainId调用工资表列表接口
          if (mainRecord.id) {
            const salaryResponse = await getAction(this.url.cwSyrygzb.list, {
              id: mainRecord.id
            })

            if (salaryResponse.success) {
              this.cwSyrygzbTable.dataSource = salaryResponse.result.records || []
            } else {
              this.$message.warning('获取工资表数据失败：' + (salaryResponse.message || '未知错误'))
              this.cwSyrygzbTable.dataSource = []
            }
          } else {
            this.$message.warning('未获取到工资表关联ID，无法加载数据')
            this.cwSyrygzbTable.dataSource = []
          }
        } else {
          // 接口返回失败（如无数据），显示警告并清空子表
          this.$message.warning(yearResponse.message || '该年度暂无数据')
          this.cwSyrygzbTable.dataSource = []
          this.model.id = undefined;

        }
      } catch (error) {
        // 异常处理
        console.error('查询接口异常：', error)
        this.$message.error('查询失败，请刷新页面重试或联系管理员')
        this.cwSyrygzbTable.dataSource = []
      } finally {
        // 关闭加载状态（无论成功/失败）
        this.confirmLoading = false
        this.cwSyrygzbTable.loading = false
      }
    }
  }
}
</script>

<style scoped></style>